package com.yc.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.study.entity.Course;
import com.yc.study.entity.CourseMaterials;
import com.yc.study.entity.User;
import com.yc.study.exception.BusinessException;
import com.yc.study.mapper.CourseMapper;
import com.yc.study.mapper.CourseMaterialsMapper;
import com.yc.study.mapper.UserMapper;
import com.yc.study.service.ICourseService;
import com.yc.study.vo.CourseVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 课程管理  服务实现类
 *
 * @author 王妍
 * @since 2022-02-20
 */
@Service
@AllArgsConstructor
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

  private final CourseMapper courseMapper;
  private final CourseMaterialsMapper courseMaterialsMapper;
  private final UserMapper userMapper;

  @Override
  public Page<CourseVo> loadPage(Page<CourseVo> courseVoPage, CourseVo course) {
    return courseMapper.loadPageVo(courseVoPage, course);
  }

  @Override
  public Page<CourseVo> getSubscribed(Long studentId, Page<CourseVo> coursePage, CourseVo course) {
    return courseMapper.selectgetScribed(studentId, coursePage, course, true);
  }

  @Override
  public Page<CourseVo> getNoSubscribed(
      Long studentId, Page<CourseVo> coursePage, CourseVo course) {
    return courseMapper.selectgetScribed(studentId, coursePage, course, false);
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public void save(CourseVo courseInfo, String teacherName) {
    final Course course = new Course();
    BeanUtils.copyProperties(courseInfo, course);
    final Long teacherId =
            Optional.ofNullable(
                            userMapper.selectOne(
                                    new LambdaQueryWrapper<User>().eq(User::getUsername, teacherName)))
                    .map(User::getId)
                    .orElseThrow(() -> new BusinessException("用户不存在！！！"));
    course.setTeacherId(teacherId);
    saveOrUpdate(course);
    // 删除原来的数据
    courseMaterialsMapper.delete(
        new LambdaQueryWrapper<CourseMaterials>().eq(CourseMaterials::getCourseId, course.getId()));
    courseInfo.getMaterialList().stream()
        .peek(courseMaterials -> courseMaterials.setCourseId(course.getId()))
        .forEach(courseMaterialsMapper::insert);
  }
}
